package com.jtbd.service.impl;

import com.jtbd.constants.*;
import com.jtbd.domain.UserEmployee;
import com.jtbd.domain.UserInfo;
import com.jtbd.dto.CampusCreateHttpDto;
import com.jtbd.dto.db.UserEmployeeInfo;
import com.jtbd.service.CampusManagementService;
import com.jtbd.service.campus.CampusService;
import com.jtbd.service.UserEmployeeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CampusManagementServiceImpl implements CampusManagementService {
    @Resource
    private CampusService campusService;
    @Resource
    private UserEmployeeService userEmployeeService;

    @Override
    @Transactional
    public long addCampus(CampusCreateHttpDto campusCreateHttpDto) {
        Long campusAddResult = campusService.addCampus(campusCreateHttpDto.getCampus());
        if (campusAddResult > 0) {
            return userEmployeeService.addUserEmployee(createCampusAdminUser(campusCreateHttpDto.getPhone(), campusCreateHttpDto.getCampus().getId()));
        }
        return 0;
    }

    /**
     * 创建校区管理员用户
     *
     * @param phone    手机号码
     * @param campusId 校区ID
     * @return UserEmployeeInfo 用户员工信息对象
     */
    private UserEmployeeInfo createCampusAdminUser(String phone, Long campusId) {
        // 创建用户员工信息对象
        UserEmployeeInfo userEmployeeInfo = new UserEmployeeInfo();
        UserInfo userInfo = new UserInfo();
        userInfo.setPassword(CommonConstant.USER_DEFAULT_PASSWORD);
        userInfo.setPhone(phone);
        userInfo.setUserType(UserTypeEnum.EMPLOYEE.getCode());
        userInfo.setUsername("校区管理员");
        userEmployeeInfo.setUserInfo(userInfo);

        // 设置员工信息
        UserEmployee employee = new UserEmployee();
        employee.setCampusId(campusId);
        employee.setDepartmentId(DepartmentCommonEnum.CAMPUS_DEPARTMENT.getCode());
        employee.setEmployeeDepartmentIdentity(EmployeeDepartmentIdentityEnum.DEPARTMENT_LEADER.getCode());
        employee.setEmployeeStatus(StatusConstant.NORMAL);
        userEmployeeInfo.setUserEmployee(employee);
        return userEmployeeInfo;
    }

}
